/* eslint-disable @typescript-eslint/no-explicit-any */

import React, { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import CommandRegistry from "./CommandRegistry";
import MenuRegistry from "./MenuRegistry";

let globalMenuRef: HTMLElement | null = null;
let globalRootRef: any = null;

const useContextMenu = (menuId: string) => {
  const [pos, setPos] = useState({ x: 0, y: 0 });
  const [ctx, setCtx] = useState(null);

  const removeOldMenu = () => {
    if (globalRootRef) {
      globalRootRef.unmount();
      globalRootRef = null;
    }
    if (globalMenuRef) {
      document.body.removeChild(globalMenuRef);
      globalMenuRef = null;
    }
  };

  useEffect(() => {
    removeOldMenu();
    if (!ctx) return;

    // 创建菜单容器元素
    globalMenuRef = document.createElement("div");
    document.body.appendChild(globalMenuRef);

    const items = MenuRegistry.getMenu(menuId, ctx);
    const menu = (
      <div
        style={{
          position: "absolute",
          top: pos.y,
          left: pos.x,
          border: "1px solid black",
          background: "#666",
          cursor: "pointer",
        }}
      >
        {items.map((item, index) => {
          return (
            <div
              key={index}
              style={{
                padding: "4px 8px",
                textDecoration: item.disabled ? "line-through" : "none",
              }}
              onClick={() => {
                if (item.disabled) return;
                CommandRegistry.execute(item.id);
                removeOldMenu();
              }}
            >
              {item.label}
            </div>
          );
        })}
      </div>
    );

    if (globalMenuRef && !globalRootRef) {
      globalRootRef = createRoot(globalMenuRef);
    }
    if (globalRootRef) {
      globalRootRef.render(menu);
    }

    return () => {
      removeOldMenu();
    };
  }, [menuId, ctx, pos.x, pos.y]);

  return (evt: React.MouseEvent, ctx: any) => {
    evt.preventDefault();
    removeOldMenu();
    setCtx(ctx);
    setPos({ x: evt.clientX, y: evt.clientY });
  };
};

export default useContextMenu;
